package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.ArticleBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadUtil.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 查询文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
       //1.参数校验
        if (dto.getArticleId() == null || dto.getAuthorId()==null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id
        ApUser apUser = AppThreadLocalUtil.getUser();
        //表示未登录
        if(apUser==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if(apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }

        Boolean isfollow=false,iscollection=false,isunlike=false,islike=false;


        //3.查看是否关注该用户
        String follow_key= BehaviorConstants.USER_FOLLOW_ +apUser.getId();
        Boolean followFlag = stringRedisTemplate.opsForHash().hasKey(follow_key, dto.getAuthorId() + "");
        isfollow=followFlag;

        //4.查询是否点赞了该文章
        String likes_key=BehaviorConstants.USER_LIKES_ +dto.getArticleId();
        Boolean likesFlag = stringRedisTemplate.opsForHash().hasKey(likes_key, apUser.getId() + "");
        islike=likesFlag;
        
        //5.查询是否不喜欢该文章
        String unlikes_key=BehaviorConstants.USER_UNLIKES_+dto.getArticleId();
        Boolean unlikesFlag = stringRedisTemplate.opsForHash().hasKey(unlikes_key, apUser.getId() + "");
        isunlike=unlikesFlag;

        //6.查看是否收藏了该文章
        String collection_key=BehaviorConstants.USER_COLLECTION_+dto.getArticleId();
        Boolean collectionFlag = stringRedisTemplate.opsForHash().hasKey(collection_key, apUser.getId() + "");
        iscollection=collectionFlag;

        //7.返回数据
        Map map=new HashMap();
        map.put("isfollow",isfollow);
        map.put("iscollection",iscollection);
        map.put("isunlike",isunlike);
        map.put("islike",islike);

        return ResponseResult.okResult(map);
    }
}
